package com.codebo.homiematchbackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codebo.homiematchbackend.common.ErrorCode;
import com.codebo.homiematchbackend.exception.ThrowUtils;
import com.codebo.homiematchbackend.mapper.ChatMapper;
import com.codebo.homiematchbackend.model.dto.chat.ChatRequest;
import com.codebo.homiematchbackend.model.entity.Chat;
import com.codebo.homiematchbackend.model.entity.TeamUser;
import com.codebo.homiematchbackend.model.enums.ChatTypeEnum;
import com.codebo.homiematchbackend.model.vo.ChatRecordVO;
import com.codebo.homiematchbackend.model.vo.ChatVO;
import com.codebo.homiematchbackend.service.ChatService;
import com.codebo.homiematchbackend.service.TeamService;
import com.codebo.homiematchbackend.service.TeamUserService;
import com.codebo.homiematchbackend.service.UserService;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 25912
 * @description 针对表【chat(聊天消息)】的数据库操作Service实现
 * @createDate 2025-09-27 16:50:12
 */
@Service
public class ChatServiceImpl extends ServiceImpl<ChatMapper, Chat>
        implements ChatService
{
    @Resource
    private TeamService teamService;

    @Resource
    private TeamUserService teamUserService;

    @Resource
    private ChatMapper chatMapper;

    @Resource
    private UserService userService;

    @Override
    public boolean sendMessage(ChatRequest chatRequest)
    {
        Long fromId = chatRequest.getFromId();
        Long toId = chatRequest.getToId();
        String text = chatRequest.getText();
        Integer chatType = chatRequest.getChatType();
        Long teamId = chatRequest.getTeamId();

        ThrowUtils.throwIf(chatType == null || ChatTypeEnum.getEnumByValue(chatType) == null, ErrorCode.PARAMS_ERROR, "聊天类型错误");
        // 如果是群聊
        if (ChatTypeEnum.GROUP_CHAT.equals(ChatTypeEnum.getEnumByValue(chatRequest.getChatType())))
        {
            //判断群聊id
            ThrowUtils.throwIf(teamService.getById(teamId) == null, ErrorCode.PARAMS_ERROR, "群聊不存在");
        } else
        {
            //判断用户id
            ThrowUtils.throwIf(userService.getById(fromId) == null || userService.getById(toId) == null, ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        ThrowUtils.throwIf(text == null || text.length() > 150, ErrorCode.PARAMS_ERROR, "消息内容过长");

        Chat chat = new Chat();
        BeanUtil.copyProperties(chatRequest, chat);
        boolean save = this.save(chat);
        ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR);
        return true;


    }

    @Override
    public List<ChatRecordVO> getChatRecord(Long userId)
    {
        //查询用户加入的队伍
        QueryWrapper<TeamUser> teamUserQueryWrapper = new QueryWrapper<>();
        teamUserQueryWrapper.eq("user_id", userId)
                .select("team_id");
        List<Long> teamIdList = teamUserService.list(teamUserQueryWrapper)
                .stream()
                .map(TeamUser::getTeamId)
                .collect(Collectors.toList());
        List<Chat> chatRecord = chatMapper.getChatRecord(userId, teamIdList);
        List<ChatRecordVO> chatRecordVO = this.getChatRecordVO(chatRecord, userId);
        System.out.println("chatRecord = " + chatRecord);
        System.out.println("chatRecordVO = " + chatRecordVO);
        return chatRecordVO;

    }


    @Override
    public List<ChatRecordVO> getChatRecordVO(List<Chat> chatList, Long currentUserId) {
        // 1. 按对话维度分组（原逻辑不变）
        Map<String, List<Chat>> groupMap = chatList.stream()
                .collect(Collectors.groupingBy(chat -> {
                    if (chat.getChatType() == 1) {          // 私聊
                        long min = Math.min(chat.getFromId(), chat.getToId());
                        long max = Math.max(chat.getFromId(), chat.getToId());
                        return "u" + min + "-" + max;
                    } else {                                // 群聊
                        return "t" + chat.getTeamId();
                    }
                }));

        // 2. 每组转一个 ChatRecordVO
        List<ChatRecordVO> result = new ArrayList<>();
        for (Map.Entry<String, List<Chat>> entry : groupMap.entrySet()) {
            List<Chat> oneGroup = entry.getValue();
            Chat any = oneGroup.get(0);

            ChatRecordVO vo = new ChatRecordVO();
            // 组内消息仍按时间倒序，方便前端直接渲染
            vo.setChatVO(oneGroup.stream()
                    .map(this::getChatVO)
                    .sorted(Comparator.comparing(ChatVO::getCreateTime))
                    .collect(Collectors.toList()));

            if (any.getChatType() == 1) {
                long targetUid = any.getFromId().equals(currentUserId)
                        ? any.getToId() : any.getFromId();
                vo.setTargetUserVO(userService.getUserVO(userService.getById(targetUid)));
            } else {
                vo.setTargetTeamVO(teamService.getTeamVO(teamService.getById(any.getTeamId())));
            }
            result.add(vo);
        }

        // 3. 会话维度：越新的越靠后
        result.sort(Comparator.comparing(
                (ChatRecordVO r) -> r.getChatVO().get(0).getCreateTime(),
                Comparator.reverseOrder()));
        return result;
    }

    @Override
    public ChatVO getChatVO(Chat chat)
    {
        ChatVO chatVO = new ChatVO();
        BeanUtil.copyProperties(chat, chatVO);
        return chatVO;
    }
}




